package com.quanyan.club.operate.service.impl;

import com.github.ltsopensource.core.json.JSON;
import com.quanyan.api.APIRequest;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.api.enums.AssetsType;
import com.quanyan.assets.request.ReqUserAccumulateModify;
import com.quanyan.assets.service.UserAssetsService;
import com.quanyan.club.constants.ClubConstants;
import com.quanyan.club.entity.db.*;
import com.quanyan.club.entity.vo.req.movement.ReqClubListInfo;
import com.quanyan.club.mapper.*;
import com.quanyan.club.mq.constant.MqConstant;
import com.quanyan.club.mq.producer.BatchGiveOutEggsProducer;
import com.quanyan.club.operate.entity.LastMemberAndEgg;
import com.quanyan.club.operate.entity.UserMsg;
import com.quanyan.club.operate.entity.req.yearactivity.ReqEnergyOrClickEgg;
import com.quanyan.club.operate.entity.resp.yearactivity.RespEnergyHomePage;
import com.quanyan.club.operate.service.ClubYearActivityService;
import com.quanyan.club.service.ClubMemberService;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.mq.client.reqeust.MqRequestMsg;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author xian-guo
 * @email 498152332@qq.com
 * @date 2016/12/29.
 */
@Service("clubYearActivityService")
public class ClubYearActivityServiceImpl implements ClubYearActivityService {

    public static final Logger logger = LoggerFactory.getLogger(ClubYearActivityServiceImpl.class);

    @Autowired
    private TbClubMemberMapper tbClubMemberMapper;//俱乐部成员

    @Autowired
    private TbClubEnergyDetailMapper tbClubEnergyDetailMapper;

    @Autowired
    private TbClubEnergyMapper tbClubEnergyMapper;
    @Autowired
    private ClubMemberService clubMemberService;
    @Autowired
    private TbClubIntegralRuleMapper tbClubIntegralRuleMapper;

    @Autowired
    private ClubYearActivityMapper clubYearActivityMapper;

    @Autowired
    private BatchGiveOutEggsProducer batchGiveOutEggsProducer;//批量送鸟蛋

    @Autowired
    private UserServiceFacade userServiceFacade;//用户模块

    @Autowired
    private TbClubEnergyEggMapper tbClubEnergyEggMapper;

    @Autowired
    private UserAssetsService userAssetsService;

    /**
     * 进入砸鸟蛋首页
     * @param clubId
     * @param uId
     * @return
     */
    @Override
    public APIResponse<RespEnergyHomePage> getEnergyHomePageMessage(Integer clubId, Integer uId) {
        //是否是俱乐部成员
        if (!this.clubMemberService.isClubMember(uId, clubId)) {
            return APIResponse.returnFail("您还不是俱乐部成员，赶紧加入俱乐部吧！");
        }
        RespEnergyHomePage respEnergyHomePage = new RespEnergyHomePage();
        int priority = clubMemberService.isClubMasterMember(uId, clubId) ? 1 : 0;//1主席
        respEnergyHomePage.setIsMaster((byte) priority);
        //当前鸟蛋总数
        TbClubIntegralRule tbClubIntegralRule = tbClubIntegralRuleMapper.selectByPrimaryKey(9);
        respEnergyHomePage.setAllEgg(Integer.valueOf(tbClubIntegralRule.getFinishGrade()));
        //该登录用户是否充过能
        TbClubEnergyDetailExample tbClubEnergyDetailExample = new TbClubEnergyDetailExample();
        tbClubEnergyDetailExample.createCriteria().andUserIdEqualTo(uId).andCreateTimeGreaterThanOrEqualTo(DateUtils.getTimesmorning()).andCreateTimeLessThan(DateUtils.getTimesnight());//
        int tbClubEnergyCount = tbClubEnergyDetailMapper.countByExample(tbClubEnergyDetailExample);
        respEnergyHomePage.setIsCharge((byte) tbClubEnergyCount);//充过能1，没充能0
        //该俱乐部是否添加到表，没有则插入表
        TbClubEnergyExample tbClubEnergyExample = new TbClubEnergyExample();
        tbClubEnergyExample.createCriteria().andClubIdEqualTo(clubId);
        int clubCountNum = tbClubEnergyMapper.countByExample(tbClubEnergyExample);
        if (clubCountNum == 0) {//表中没记录
            TbClubEnergy tbClubEnergy = new TbClubEnergy();
            tbClubEnergy.setClubId(clubId);
            //查找俱乐部主席
            TbClubMemberExample tbClubMemberExample = new TbClubMemberExample();
            tbClubMemberExample.createCriteria().andClubIdEqualTo(clubId).andPriorityEqualTo(1).andIsDeleteEqualTo((byte) 0);
            List<TbClubMember> tbClubMembers = tbClubMemberMapper.selectByExample(tbClubMemberExample);
            if (CollectionUtils.isEmpty(tbClubMembers)) {
                return APIResponse.returnFail(ApiResponseEnum.INTERNAL_ERROR);
            }
            tbClubEnergy.setUserId(tbClubMembers.get(0).getUid());
            int insertCount = tbClubEnergyMapper.insertSelective(tbClubEnergy);//插入表
            if (insertCount == 0) {
                return APIResponse.returnFail(ApiResponseEnum.INTERNAL_ERROR);
            }
        }
        //今日是否有敲鸟蛋机会
        if (priority == 1) {
            respEnergyHomePage.setRemainCount((byte) 1);
            tbClubEnergyExample.clear();
            tbClubEnergyExample.createCriteria().andUserIdEqualTo(uId);
            List<TbClubEnergy> tbClubEnergyList = tbClubEnergyMapper.selectByExample(tbClubEnergyExample);
            if (CollectionUtils.isEmpty(tbClubEnergyList)) {
                return APIResponse.returnFail(ApiResponseEnum.FAIL);
            }
            for (TbClubEnergy tbClubEnergy : tbClubEnergyList) {
                if (0 == tbClubEnergy.getClickTime()) {//今日用过砸机会
                    respEnergyHomePage.setRemainCount((byte) 0);
                }
            }
        }
        //当前充能人数
        tbClubEnergyDetailExample.clear();
        tbClubEnergyDetailExample.createCriteria().andClubIdEqualTo(clubId).andIsChargeEqualTo((byte) 1);
        int energyCount = tbClubEnergyDetailMapper.countByExample(tbClubEnergyDetailExample);
        respEnergyHomePage.setEnergyCount(energyCount);
        //能量点上线
        TbClubIntegralRule tbClubIntegralRules = tbClubIntegralRuleMapper.selectByPrimaryKey(6);
        int maxEnergyNum = Integer.valueOf(tbClubIntegralRules.getFinishGrade());
        respEnergyHomePage.setClubCount(maxEnergyNum);
        //查询用户信息
        APIResponse<RespUserInfoBase> apiResponse = userServiceFacade.queryUserInfo(uId);
        if (apiResponse.isRet()) {
            RespUserInfoBase respUserInfoBase = apiResponse.getData();
            respEnergyHomePage.setIcon(respUserInfoBase.getIcon());
            respEnergyHomePage.setUserNick(respUserInfoBase.getNickName());
        }
        return APIResponse.returnSuccess(respEnergyHomePage);
    }

    /**
     * 充能 or 砸鸟蛋
     *
     * @param reqEnergyOrClickEgg
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse chargeEnergyOrClickEgg(ReqEnergyOrClickEgg reqEnergyOrClickEgg) {
        //活动未开始可以充能
        if (this.getActivityStartTime() == 2) {
            return APIResponse.returnFail("活动已经结束了，感谢您的参与！");
        }
        //不是俱乐部成员，非法请求
        if (!this.clubMemberService.isClubMember(reqEnergyOrClickEgg.getuId(), reqEnergyOrClickEgg.getClubId())) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        int userType = clubMemberService.isClubMasterMember(reqEnergyOrClickEgg.getuId(), reqEnergyOrClickEgg.getClubId()) ? 1 : 0;
        if (reqEnergyOrClickEgg.getType() == 0) {//充能
            //判断库存还有没有鸟蛋
            TbClubIntegralRule tbClubIntegralRule = tbClubIntegralRuleMapper.selectByPrimaryKey(9);
            int allEggNum = Integer.valueOf(tbClubIntegralRule.getPoint());
            logger.warn(reqEnergyOrClickEgg.getClubId() + "--当前库存--" + allEggNum);
            if (allEggNum <= 0) {
                return APIResponse.returnFail("鸟蛋已被其他主席占坑，不能再充能了哦！快去砸蛋消耗剩下的能量值吧！");
            }
            //判断能量点是否超过最高定数
            TbClubEnergyDetailExample tbClubEnergyDetailExample = new TbClubEnergyDetailExample();
            tbClubEnergyDetailExample.createCriteria().andClubIdEqualTo(reqEnergyOrClickEgg.getClubId()).andIsChargeEqualTo((byte) 1);
            int energyNum = tbClubEnergyDetailMapper.countByExample(tbClubEnergyDetailExample);
            TbClubIntegralRule tbClubIntegralRules = tbClubIntegralRuleMapper.selectByPrimaryKey(6);
            int maxEnergyNum = Integer.valueOf(tbClubIntegralRules.getFinishGrade());
            if (energyNum >= maxEnergyNum) {
                if (userType == 1) {//主席
                    return APIResponse.returnFail("锤子的能量值已经爆满了，赶紧去砸鸟蛋吧！");
                }
                return APIResponse.returnFail("锤子的能量值已经爆满了，等主席砸完鸟蛋再充吧！");
            }
            //今天是否充过能
            tbClubEnergyDetailExample.clear();
            tbClubEnergyDetailExample.createCriteria().andUserIdEqualTo(reqEnergyOrClickEgg.getuId())
                    .andCreateTimeGreaterThanOrEqualTo(DateUtils.getTimesmorning()).andCreateTimeLessThan(DateUtils.getTimesnight());
            int tbClubEnergyDetailCount = tbClubEnergyDetailMapper.countByExample(tbClubEnergyDetailExample);
            if (tbClubEnergyDetailCount > 0) {
                return APIResponse.returnFail("今日已充过能了，请明天再充吧！");
            }
            //没充能，插入记录
            TbClubEnergyDetail tbClubEnergyDetail = new TbClubEnergyDetail();
            tbClubEnergyDetail.setUserId(reqEnergyOrClickEgg.getuId());
            tbClubEnergyDetail.setClubId(reqEnergyOrClickEgg.getClubId());
            tbClubEnergyDetail.setUserType((byte) userType);
            int insertCount = tbClubEnergyDetailMapper.insertSelective(tbClubEnergyDetail);
            if (insertCount == 0) {
                return APIResponse.returnFail("充能失败，请重试！");
            }
            //减少鸟蛋库存
            int upEggP = clubYearActivityMapper.updateYearActivityEggP(10);
            if (upEggP <= 0) {
                throw new BizException("充能失败,鸟蛋已经被别人捷足先登了！");
            }
            return APIResponse.returnSuccess("充能成功");
        } else if (reqEnergyOrClickEgg.getType() == 1 && userType == 1) {//砸鸟蛋
            //检查活动是否开始
            if (this.getActivityStartTime() == 1) {
                return APIResponse.returnFail("活动还没开始呢,再等等吧！");
            }
            //今日有没有砸鸟蛋的机会
            TbClubEnergyExample tbClubEnergyExample = new TbClubEnergyExample();
            tbClubEnergyExample.createCriteria().andUserIdEqualTo(reqEnergyOrClickEgg.getuId());
            List<TbClubEnergy> tbClubEnergyList = tbClubEnergyMapper.selectByExample(tbClubEnergyExample);
            if (CollectionUtils.isEmpty(tbClubEnergyList)) {
                return APIResponse.returnFail(ApiResponseEnum.ILLEGAL_PROTOCOL);
            }
            for (TbClubEnergy tbClubEnergy : tbClubEnergyList) {
                if (0 == tbClubEnergy.getClickTime()) {//今日用过砸机会
                    return APIResponse.returnFail("今日砸鸟蛋次数已用完，请明日再试！");
                }
            }
            //充能点数
            TbClubEnergyDetailExample tbClubEnergyDetailExample = new TbClubEnergyDetailExample();
            tbClubEnergyDetailExample.createCriteria().andClubIdEqualTo(reqEnergyOrClickEgg.getClubId()).andIsChargeEqualTo((byte) 1);
            tbClubEnergyDetailExample.setOrderByClause(" create_time ASC");
            List<TbClubEnergyDetail> tbClubEnergyDetails = tbClubEnergyDetailMapper.selectByExample(tbClubEnergyDetailExample);
            if (CollectionUtils.isEmpty(tbClubEnergyDetails) || tbClubEnergyDetails.size() < 10) {
                return APIResponse.returnFail("当前充能点数不满10个点，请继续充能后再试！");
            }
            logger.warn("---------充能点数-------" + tbClubEnergyDetails.size());
            //跟新充能人状态
            List<Integer> idsList = new ArrayList<>();
            List<TbClubEnergyDetail> tbClubEnergyDe = new ArrayList<>();//排除主席的充能人集合
            int isMaster = 0;
            for (TbClubEnergyDetail tbClubEnergyDetail : tbClubEnergyDetails) {
                idsList.add(tbClubEnergyDetail.getClubId());
                if (!reqEnergyOrClickEgg.getuId().equals(tbClubEnergyDetail.getUserId())) {
                    tbClubEnergyDe.add(tbClubEnergyDetail);
                } else {
                    isMaster ++;//主席充能了
                }
            }
            int batchNum = clubYearActivityMapper.bitchUpdateEggNum(idsList);
            if (batchNum <= 0) {
                throw new BizException("砸鸟蛋失败,砸鸟蛋的机会已经被别人捷足先登了");
            }
            //跟新剩余鸟蛋数
            int consumeEgg=0;
            if(tbClubEnergyDe.size()==0){//只有主席充能
                consumeEgg=tbClubEnergyDetails.size();
                //回收除去主席的剩余鸟蛋库存
                int upEggAdd = clubYearActivityMapper.updateYearActivityEggAdd(tbClubEnergyDetails.size() * 10-consumeEgg);
                if (upEggAdd <= 0) {
                    throw new BizException("砸鸟蛋失败,砸鸟蛋的机会已经被别人捷足先登了");
                }
            }else{
                consumeEgg=tbClubEnergyDetails.size() * 10;
            }
            int upEggG = clubYearActivityMapper.updateYearActivityEggG(consumeEgg);
            if (upEggG <= 0) {
                throw new BizException("砸鸟蛋失败，鸟蛋已经被别人捷足先登了");
            }
            Map<Integer, Long> egg4User=new HashMap<>();
            //如果全是主席，回收剩余鸟蛋
            if(tbClubEnergyDe.size()!=0){
                //计算每个人获得的鸟蛋数，排除主席的
                egg4User = this.assignEgg(tbClubEnergyDe, isMaster);
            }
            //加入主席的
            egg4User.put(reqEnergyOrClickEgg.getuId(), (long) (tbClubEnergyDetails.size()));
            logger.warn("---------鸟蛋数分配-------------" + JSON.toJSONString(egg4User));
            //插入鸟蛋记录
            List<UserMsg> userMsgList = new ArrayList<>();//批量插入鸟蛋记录
            for (Map.Entry<Integer, Long> entry : egg4User.entrySet()) {
                UserMsg u = new UserMsg();
                u.setUserId(entry.getKey());
                u.setEggNum(entry.getValue());
                u.setClubId(reqEnergyOrClickEgg.getClubId());
                userMsgList.add(u);
            }
            clubYearActivityMapper.insertEnergyEgg(userMsgList);
            //今日砸鸟蛋次数已用完，更新数据砸鸟蛋次数
            int countUpTimes = clubYearActivityMapper.updateClubClickTimes(reqEnergyOrClickEgg.getClubId());
            if (countUpTimes <= 0) {
                throw new BizException("砸鸟蛋失败，砸鸟蛋的机会已经被别人捷足先登了");
            }
            // /掉用户中心批量更新鸟蛋
            logger.warn("---砸鸟蛋发送鸟蛋给用户--");
            this.sendEggToUser(egg4User, userMsgList);
            return APIResponse.returnSuccess(tbClubEnergyDetails.size());
        } else {
            //检查活动是否开始
            if (this.getActivityStartTime() == 1) {
                return APIResponse.returnFail("活动还没开始呢,再等等吧！");
            }
            return APIResponse.returnFail(ApiResponseEnum.PERMISSION_DENIED);
        }
    }

    /**
     * 分发鸟蛋算法
     *
     * @param tbClubEnergyDetails
     * @param isMaster
     * @return
     */
    private Map<Integer, Long> assignEgg(List<TbClubEnergyDetail> tbClubEnergyDetails, int isMaster) {
        Map<Integer, Long> paramMap = new HashMap<>();
        int energyNum = tbClubEnergyDetails.size()+ isMaster;//充能人数(排除了主席如果主席充能的话)
        int allEggNum = energyNum * 10;//总鸟蛋数
        int allCustormEggNum = allEggNum - energyNum;//分给普通成员的鸟蛋
        energyNum = energyNum - isMaster;
        int randomEggNum = allCustormEggNum - energyNum * 5;
        LastMemberAndEgg lastMember = new LastMemberAndEgg(energyNum, randomEggNum);
        logger.warn("--应分配的成员数：--" + energyNum + "--应分配的鸟蛋--" + randomEggNum);
        for (int i = 0; i < energyNum; i++) {
            Integer userId=tbClubEnergyDetails.get(i).getUserId();
            if (paramMap.containsKey(userId)){
                Long value=paramMap.get(userId)+this.getRandomMoney(lastMember) + 5L;
                paramMap.put(userId,value);
                continue;
            }
            paramMap.put(tbClubEnergyDetails.get(i).getUserId(), this.getRandomMoney(lastMember) + 5L);
        }
        return paramMap;
    }

    /**
     * remainSize 剩余人数
     * remainMoney  剩余鸟蛋数
     *
     * @return
     */
    private int getRandomMoney(LastMemberAndEgg lastMember) {
        if (lastMember.remainSize == 0) {
            return lastMember.remainSize;
        }
        if (lastMember.remainMoney == 0) {
            return lastMember.remainMoney;
        }
        if (lastMember.remainSize == 1) {
            lastMember.remainSize--;
            return lastMember.remainMoney;
        }
        Random r = new Random();
        //int min = 5; //
        int max = lastMember.remainMoney / lastMember.remainSize * 2;
        int money = (int) (r.nextDouble() * max);
        //money = money <= min ? 5 : money;
        lastMember.remainSize--;
        lastMember.remainMoney -= money;
        return money;
    }

    /**
     * 发送mq到资产中心
     *
     * @param egg4User
     */
    private void sendEggToUser(Map<Integer, Long> egg4User, List<UserMsg> userMsgList) {
        List<RespUserInfoBase> respUserInfoBases=new ArrayList<>();
        List<Integer> uidList = new ArrayList<>();
        if (egg4User.size() >= 50) {
            int pageSize = 50;
            int pageT = egg4User.size() / pageSize;
            for (int i = 1; i <= pageT; i++) {
                for (int j = pageSize * (i - 1); j < i * pageSize; j++) {
                    uidList.add(userMsgList.get(j).getUserId());
                }
                APIResponse<List<RespUserInfoBase>> apiUserResponse = userServiceFacade.batchQueryUserInfo(uidList);
                if (!apiUserResponse.isRet()) {
                    throw new BizException("批量查询用户中心失败了sendEggToUser");
                }
                respUserInfoBases.addAll(apiUserResponse.getData());
                uidList.clear();
            }
            int pageEnd = egg4User.size() % pageSize;//算最后的余数
            if (pageEnd>0){
                for(int i=userMsgList.size()-pageEnd;i<userMsgList.size();i++){
                    uidList.add(userMsgList.get(i).getUserId());
                }
                APIResponse<List<RespUserInfoBase>> apiUserResponse = userServiceFacade.batchQueryUserInfo(uidList);
                if (!apiUserResponse.isRet()) {
                    throw new BizException("批量查询用户中心失败了sendEggToUser");
                }
                respUserInfoBases.addAll(apiUserResponse.getData());
            }
        }else{
            for (Map.Entry<Integer, Long> entry : egg4User.entrySet()) {
                uidList.add(entry.getKey());
            }
            APIResponse<List<RespUserInfoBase>> apiUserResponse = userServiceFacade.batchQueryUserInfo(uidList);
            if (!apiUserResponse.isRet()) {
                throw new BizException("批量查询用户中心失败了sendEggToUser");
            }
            respUserInfoBases.addAll(apiUserResponse.getData());
        }
        logger.warn("------sendEggToUser-查询用户信息-------"+JSON.toJSONString(respUserInfoBases.size()));
        List<ReqUserAccumulateModify> reqUserAccumulateModifies = new ArrayList<>();
        for (Map.Entry<Integer, Long> entry : egg4User.entrySet()) {
            ReqUserAccumulateModify modify = new ReqUserAccumulateModify();
            modify.setUid(entry.getKey());
            modify.setAccumulate(entry.getValue());
            modify.setAssetsType(AssetsType.ASSETS_EGGS.id.byteValue());
            modify.setSystemCode(Constants.CLUB_SYSTEM_CODE);
            modify.setBusinessCode(ClubConstants.CLUB_YEAR_ACTIVITY_CODE);
            for (RespUserInfoBase respUserInfoBase : respUserInfoBases) {
                if (entry.getKey().equals(respUserInfoBase.getUid())) {
                    modify.setReceiver(respUserInfoBase.getNickName());
                    break;
                }
            }
            modify.setPayReceive("活动奖励");
            modify.setInfo("全民充能，主席砸蛋");
            reqUserAccumulateModifies.add(modify);
        }
        APIRequest<List<ReqUserAccumulateModify>> apiRequest=new APIRequest<>();
        apiRequest.setData(reqUserAccumulateModifies);
        APIResponse apiResponse=userAssetsService.batchModifyEgg(apiRequest);
        if (!apiResponse.isRet()){
            throw new BizException("批量送鸟蛋失败");
        }
    }

    /**
     * 获取俱乐部充能人数
     *
     * @param reqClubListInfo
     * @return
     */
    @Override
    public APIResponse<PageObj<List<UserMsg>>> getChargeEnergyMember(ReqClubListInfo reqClubListInfo) {
        Map<String, Object> paramMap = reqClubListInfo.getParamMap();
        paramMap.put("pageNum", reqClubListInfo.getPageNum() * reqClubListInfo.getPageSize());
        paramMap.put("pageSize", reqClubListInfo.getPageSize());
        List<TbClubEnergyDetail> tbClubEnergyDetailList = clubYearActivityMapper.selectEnergyMember(paramMap);
        if (CollectionUtils.isEmpty(tbClubEnergyDetailList) || null == tbClubEnergyDetailList.get(0)) {
            return APIResponse.returnSuccess();
        }
        logger.warn("---getChargeEnergyMember----" + JSON.toJSONString(tbClubEnergyDetailList));
        List<Integer> userIdList = new ArrayList<>();
        for (TbClubEnergyDetail tbClubEnergyDetail : tbClubEnergyDetailList) {
            userIdList.add(tbClubEnergyDetail.getUserId());
        }
        APIResponse<List<RespUserInfoBase>> apiUserInfo = userServiceFacade.batchQueryUserInfo(userIdList);
        if (!apiUserInfo.isRet()) {
            return APIResponse.returnFail("查询用户信息失败");
        }
        List<RespUserInfoBase> respUserInfoBaseList = apiUserInfo.getData();
        List<UserMsg> userMsgList = new ArrayList<>();
        for (RespUserInfoBase respUserInfoBase : respUserInfoBaseList) {
            UserMsg userMsg = new UserMsg();
            userMsg.setIcon(respUserInfoBase.getIcon());
            userMsg.setUserName(respUserInfoBase.getNickName());
            userMsgList.add(userMsg);
        }
        int totalCount = clubYearActivityMapper.selectEnergyMemberCount((Integer) paramMap.get("clubId"));
        return APIResponse.returnSuccess(PageObj.create(totalCount, reqClubListInfo.getPageNum(), reqClubListInfo.getPageSize(), userMsgList));
    }

    /**
     * 判断活动是否开始
     *
     * @return
     */
    private int getActivityStartTime() {
        TbClubIntegralRule tbClubIntegralRule = tbClubIntegralRuleMapper.selectByPrimaryKey(7);
        String startTime = tbClubIntegralRule.getFinishGrade();
        String endTime = tbClubIntegralRule.getPoint();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return this.compareDate(simpleDateFormat.parse(startTime), simpleDateFormat.parse(endTime));
        } catch (ParseException e) {
            e.printStackTrace();
            return 2;
        }
    }

    /**
     * 判断活动是否开始
     *
     * @param start
     * @param end
     * @return
     */
    private int compareDate(Date start, Date end) {
        Date today = new Date();
        if (today.getTime() < start.getTime()) {
            return 1;
        }
        if (today.getTime() > end.getTime()) {
            return 2;
        }
        return 0;
    }

    /**
     * \计算现在到明天凌晨的秒数
     *
     * @return
     */
    private int compareDate() {
        Date today = new Date();
        long difTime = DateUtils.getTimesnight().getTime() + 1000 - today.getTime();
        return (int) (difTime / 1000);
    }

}
